package com.example.demo;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DBConnection {

    private static final Logger logger = LoggerFactory.getLogger(DBConnection.class);


    /**
     * 功能描述:
     * 〈获取数据库连接〉
     *
     * @param driver 1
     * @param url 2
     * @param user 3
     * @param password 4
     * @return : java.sql.Connection
     * @author : zach
     * @date : 2020/6/28 16:47
     */
    public static Connection getConnection(String driver, String url, String user, String password){
        Connection conn = null;
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, user, password);
            return conn;
        } catch (Exception e) {
            logger.error("数据库连接失败，原因是" + e.getMessage());
            return conn;
        }
    }



    /**
     * 功能描述:
     * 〈将ResultSet转换为Map格式〉
     *
     * @param rs 1
     * @return : java.util.Map<java.lang.String,java.lang.String>
     * @author : zach
     * @date : 2020/6/28 16:45
     */
    public static Map<String, String> getResultMap(ResultSet rs) throws SQLException {
        Map<String, String> hm = new HashMap<>();
        ResultSetMetaData rsmd = rs.getMetaData();
        int count = rsmd.getColumnCount();// 获取列的数量
        for (int i = 1; i <= count; i++) {
            String key = rsmd.getColumnLabel(i);
            String value = rs.getString(i);
            hm.put(key, value);
        }
        return hm;
    }


    /**
     * 功能描述:
     * 〈将ResultSet转换为List格式〉
     *
     * @param rs 1
     * @return : java.util.List<java.util.Map>
     * @author : zach
     * @date : 2020/6/28 16:46
     */
    private static List<Map> convertList(ResultSet rs) throws SQLException {
        List<Map> list = new ArrayList<>();
        ResultSetMetaData md = rs.getMetaData();//获取键名
        int columnCount = md.getColumnCount();//获取列的数量
        while (rs.next()) {
            Map<String, Object> rowData = new HashMap<>();//声明Map
            for (int i = 1; i <= columnCount; i++) {
                rowData.put(md.getColumnName(i), rs.getObject(i));//获取键名及值
            }
            list.add(rowData);
        }
        return list;
    }


    public static void main(String[] args) throws SQLException {
        String url = "";
        String driver = "";
        String username = "";
        String password = "";
        Connection conn = DBConnection.getConnection(driver,url,username,password);
        Statement st=conn.createStatement();
        ResultSet rs=st.executeQuery("select * from etl_db_info");
        while(rs.next()){
            System.out.println(rs.getString("db_info_isn")+" " +rs.getString("db_info_id"));
         }
    }

}
